package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.comment.domain.HotelComment;
import cn.wolfcode.luowowo.comment.domain.TouristComment;
import cn.wolfcode.luowowo.comment.service.IHotelCommentService;
import cn.wolfcode.luowowo.comment.service.ITouristCommentService;
import cn.wolfcode.luowowo.common.query.QueryObject;
import cn.wolfcode.luowowo.common.utils.AjaxResult;
import cn.wolfcode.luowowo.common.utils.AssertUtil;
import cn.wolfcode.luowowo.common.utils.DateUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.search.vo.MineDestVo;
import cn.wolfcode.luowowo.search.vo.MineHotalVo;
import cn.wolfcode.luowowo.search.vo.MineTouristVo;
import cn.wolfcode.luowowo.website.web.annotation.CheckLoginAnnotation;
import cn.wolfcode.luowowo.website.web.annotation.GetUserInfoAnnotation;
import cn.wolfcode.luowowo.website.web.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("mine")
public class MineController {
    @Value("${file.path}")
    private String fileBasePath;

    @Reference
    private IRedisService redisService;

    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private ITravelService travelService;
    @Reference
    private IHotelCommentService hotelCommentService;
    @Reference
    private ITouristCommentService touristCommentService;


    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;

    /**
     * 基础信息更新
     *
     * @param currentUser
     * @param user
     * @return
     */
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(@GetUserInfoAnnotation UserInfo currentUser, UserInfo user) {
        user.setId(currentUser.getId());
        user.setPhone(currentUser.getPhone());
        userInfoService.renewUserInfo(user);
        return "redirect:/mine/home";
    }

    /**
     * 上传图片
     *
     * @param user
     * @param files
     * @return
     */
    @RequestMapping("coverUpload")
    @ResponseBody
    public Object uploadImg(@GetUserInfoAnnotation UserInfo user, MultipartFile files) {
        //硬盘服务器,之前存阿里云的,阿里云好在全国有分支服务器
        String filename = UploadUtil.upload(files, fileBasePath);


        userInfoService.renewHeadImg("/" + filename, user.getId());

        user.setHeadImgUrl("/" + filename);
        String s = JSON.toJSONString(user);
        redisService.setVerifyCode(RedisKeysUtil.LOGIN_USER.join(user.getId().toString()), s, RedisKeysUtil.LOGIN_USER.getTime());
        return filename;
    }

    @RequestMapping("setting")
    @CheckLoginAnnotation
    public String setting(Model model, @GetUserInfoAnnotation UserInfo userInfo) {


        UserInfo user = userInfoService.get(userInfo.getId());
        double count = userInfoService.getSafetyIntegrity(user);
        model.addAttribute("safetyIntegrity", count);

        model.addAttribute("user", user);
        return "mine/setting";
    }

    /**
     * 主页
     *
     * @return
     */
    @RequestMapping("home")
    @CheckLoginAnnotation
    public String home(Model model, @GetUserInfoAnnotation UserInfo userInfo) {
        //用户资料
        UserInfo user = userInfoService.get(userInfo.getId());
        model.addAttribute("user", user);

        List<UserInfo> list = userInfoService.getFollowers(userInfo.getId());
        int size = list.size();

        model.addAttribute("list", list);
        model.addAttribute("size", size);
        //用户写过的游记用模板拼进去
        //点评也用模板拼过去

        return "mine/homepage";
    }

    @RequestMapping("mineTravelTPL1")
    public String mineTravelTPL(Model model, @GetUserInfoAnnotation UserInfo userInfo, QueryObject qo) {
        //用户写过的游记
        //用模板拼进去
        List<Travel> travels = travelService.listByAutorId(userInfo.getId());
        PageInfo pageInfo = travelService.queryByAutorId(userInfo.getId(), qo);

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("travels", travels);

        model.addAttribute("qo", qo);

        int size = travels.size();
        model.addAttribute("size", size);

        return "mine/mineTravelTPL";
    }

    @RequestMapping("mytravelnotes")
    @CheckLoginAnnotation
    public String mytravelnotes(Model model, @GetUserInfoAnnotation UserInfo userInfo) {
        String total = redisService.getVerifyCode(RedisKeysUtil.LOGINNUM_TOTAL.
                join(userInfo.getId().toString()));
        Integer b;

        if (total == null) {
            b = 0;
        } else {
            b = Integer.parseInt(total);
        }
        b++;

        redisService.setVerifyCode(RedisKeysUtil.LOGINNUM_TOTAL.
                join(userInfo.getId().toString()), b.toString());


        Date endDate = DateUtil.getEndDate(new Date());
        String today = redisService.getVerifyCode(RedisKeysUtil.LONGINNUM_TODAY.
                join(userInfo.getId().toString()));
        Integer a;
        if (today == null) {
            a = 0;
        } else {
            a = Integer.parseInt(today);

        }
        a++;
        redisService.setVerifyCode(RedisKeysUtil.LONGINNUM_TODAY.join(userInfo.getId().toString()), a.toString(), DateUtil.getDateBetween(new Date(), endDate));
        List<Travel> travels = travelService.listByAutorId(userInfo.getId());

        int size = travels.size();
        model.addAttribute("size", size);

        int replyNum = 0;
        int reading = 0;
        for (Travel travel : travels) {
            int reply = travel.getReplynum();
            replyNum = reply + replyNum;
            int viewnum = travel.getViewnum();
            reading = reading + viewnum;
        }
        model.addAttribute("replyNum", replyNum);
        model.addAttribute("reading", reading);


        model.addAttribute("today", a);

        model.addAttribute("total", b);


        return "mine/mytravelnotes";
    }

    @RequestMapping("mineCommentTPL")
    public String mineCommentTPL(Model model, @GetUserInfoAnnotation UserInfo userInfo) {
//        RedisKeysUtil
        List<HotelComment> hotelComment = hotelCommentService.getHotelCommentByUserId(userInfo.getId());
        model.addAttribute("hotelComment", hotelComment);

        List<TouristComment> touristComment = touristCommentService.getTouristCommnetByUserId(userInfo.getId());
        model.addAttribute("touristComment", touristComment);

        int size = hotelComment.size() + touristComment.size();

        model.addAttribute("size", size);

        return "mine/mineCommentTPL";
    }

    @Reference
    private IHotelService hotelService;
    @Reference
    private ITouristService touristService;

    @RequestMapping("commentTPL")
    public String commentTPL(Model model, @GetUserInfoAnnotation UserInfo userInfo) {
//        RedisKeysUtil
        List<HotelComment> hotelComment = hotelCommentService.getHotelCommentByUserId(userInfo.getId());

        List<MineHotalVo> hotalList = new ArrayList<>();
        for (HotelComment comment : hotelComment) {
            MineHotalVo hotalVo = new MineHotalVo();
            BeanUtils.copyProperties(comment, hotalVo);
            Hotel hotel = hotelService.get(comment.getHotelId());
            hotalVo.setHotalCover(hotel.getImg());
            hotalList.add(hotalVo);
        }
        model.addAttribute("hotelComment", hotalList);


        List<TouristComment> touristComment = touristCommentService.getTouristCommnetByUserId(userInfo.getId());

        List<MineTouristVo> touristList = new ArrayList<>();
        for (TouristComment comment : touristComment) {
            MineTouristVo touristVo = new MineTouristVo();
            BeanUtils.copyProperties(comment, touristVo);
            Travel travel = travelService.get(comment.getTouristId());
            touristVo.setTouristCover(travel.getCoverUrl());
            touristList.add(touristVo);
        }
        model.addAttribute("touristComment", touristList);

        return "mine/commentTpl";
    }


    @RequestMapping("review")
    @CheckLoginAnnotation
    public String review(@GetUserInfoAnnotation UserInfo userInfo, Model model) {
        Long count = 0L;
        List<HotelComment> hotelComment = hotelCommentService.getHotelCommentByUserId(userInfo.getId());

        List<TouristComment> touristComment = touristCommentService.getTouristCommnetByUserId(userInfo.getId());
        for (TouristComment comment : touristComment) {
            int thumbupnum = comment.getThumbupnum();
            count = thumbupnum + count;
        }

        int commentCount = hotelComment.size() + touristComment.size();
        model.addAttribute("commentCount", commentCount);
        model.addAttribute("thumbupnum", count);

        return "mine/review";
    }

    /**
     * 手机验证改密码
     *
     * @param userInfo
     * @return
     */
    @RequestMapping("mobile")
    public String mobile(@GetUserInfoAnnotation UserInfo userInfo) {
        userInfoService.send(userInfo.getPhone());
        return "mine/mobile";
    }

    @RequestMapping("resentVerifyCode")
    @ResponseBody
    public AjaxResult resentVerifyCode(@GetUserInfoAnnotation UserInfo userInfo) {
        userInfoService.send(userInfo.getPhone());
        return AjaxResult.SUCCESS;
    }

    /**
     * 修改手机号码发送验证码
     *
     * @param userInfo
     * @param phone
     * @return
     */
    @RequestMapping("getVerifyCodeforRenewPhone")
    @ResponseBody
    public AjaxResult getVerifyCodeforRenewPhone(@GetUserInfoAnnotation UserInfo userInfo, String phone) {
        if (!phone.equals(userInfo.getPhone())) {
            return AjaxResult.FAIL;
        }

        userInfoService.send(userInfo.getPhone());
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("getVerifyCodeforNewMobile")
    @ResponseBody
    public AjaxResult getVerifyCodeforNewMobile(String phone) {

        userInfoService.send(phone);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("renewMobileNumber")
    @ResponseBody
    public AjaxResult renewMobileNumber(@GetUserInfoAnnotation UserInfo currentUser, String verifyCode, String phone) {
        if (!userInfoService.VerifyCode(verifyCode, phone)) {
            return AjaxResult.FAIL;
        }

        currentUser.setPhone(phone);
        userInfoService.renewUserInfo(currentUser);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("verifyFirstVerifyCode")
    @ResponseBody
    public AjaxResult verifyFirstVerifyCode(@GetUserInfoAnnotation UserInfo userInfo, String verifyCode) {

        if (!userInfoService.VerifyCode(verifyCode, userInfo.getPhone())) {
            return AjaxResult.FAIL;
        }

        return AjaxResult.SUCCESS;
    }

    /**
     * 手机的渠道改密码
     *
     * @param userInfo
     * @param password  密码
     * @param rpassword 验证密码
     * @param smscode   验证码
     * @return
     */
    @RequestMapping("renewPasswordByPhone")
    @ResponseBody
    public AjaxResult renewPasswordByPhone(@GetUserInfoAnnotation UserInfo userInfo, String password, String rpassword, String smscode) {
        AssertUtil.chekPasswordEquals(password, rpassword);
        if (!userInfoService.VerifyCode(smscode, userInfo.getPhone())) {
            return AjaxResult.FAIL;
        }
        UserInfo userInfo1 = userInfoService.get(userInfo.getId());
        userInfo1.setPassword(password);
        userInfoService.renewUserInfo(userInfo1);
        return AjaxResult.SUCCESS;
    }


    @RequestMapping("deleteAccount")
    @ResponseBody
    public AjaxResult deleteAccount(@GetUserInfoAnnotation UserInfo userInfo) {
        userInfoService.delete(userInfo.getId());
        return AjaxResult.SUCCESS;
    }



    @CheckLoginAnnotation
    @RequestMapping("travelcollection")
    public String travelcollection(@GetUserInfoAnnotation UserInfo userInfo,Model model) {
        List<Travel> travels = travelService.getTravelByUserId(userInfo.getId());
        model.addAttribute("travels",travels);

        List<Destination> destinations = destinationService.getDestVoByUserId(userInfo.getId());
        List<MineDestVo> dest = new ArrayList<>();
        for (Destination destination : destinations) {
            MineDestVo mineDestVo = new MineDestVo();
            List<Hotel> hotels = hotelService.getHotelByThemeByDestName(destination.getName());
            mineDestVo.setDestination(destination);
            mineDestVo.setHotels(hotels);
            dest.add(mineDestVo);
        }
        model.addAttribute("dest",dest);

        List <StrategyDetail> strategyDetails = strategyDetailService.getDestVoByUserId(userInfo.getId());
        model.addAttribute("strategyDetails",strategyDetails);


        return "mine/travelcollection";
    }


}
